﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;



namespace ServicioWPF.Controles
{
    /// <summary>
    /// Lógica de interacción para UsuarioClave.xaml
    /// </summary>
    public partial class UsuarioClave
    {
        public UsuarioClave()
        {
            this.InitializeComponent();
            txtUsuario.Focus();
        }

        public static readonly RoutedEvent AutenticadoEvent = EventManager.RegisterRoutedEvent("AutenticacionExitosa", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UsuarioClave));
        public static readonly RoutedEvent ErrorAutenticacionEvent = EventManager.RegisterRoutedEvent("AutenticacionError", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UsuarioClave));
        public static readonly RoutedEvent IniciarAutenticacionEvent = EventManager.RegisterRoutedEvent("AutenticacionIniciar", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UsuarioClave));

        bool errorSesion = false;

        public event RoutedEventHandler AutenticacionExitosa
        {
            add { AddHandler(AutenticadoEvent, value); }
            remove { RemoveHandler(AutenticadoEvent, value); }
        }

        public event RoutedEventHandler AutenticacionError
        {
            add { AddHandler(ErrorAutenticacionEvent, value); }
            remove { RemoveHandler(ErrorAutenticacionEvent, value); }
        }

        public event RoutedEventHandler AutenticacionIniciar
        {
            add { AddHandler(ErrorAutenticacionEvent, value); }
            remove { RemoveHandler(ErrorAutenticacionEvent, value); }
        }

        private void btnAceptar_Click(object sender, RoutedEventArgs e)
        {
            RoutedEventArgs evento;

            if (txtUsuario.Text!=string.Empty)
            {
                errorSesion = false;
                evento = new RoutedEventArgs(UsuarioClave.AutenticadoEvent);
            }
            else
            {
                txtClave.Password = string.Empty;
                errorSesion = true;
                evento = new RoutedEventArgs(UsuarioClave.ErrorAutenticacionEvent);
            }

            RaiseEvent(evento);
        }

        private void txtUsuario_TextChanged(object sender, TextChangedEventArgs e)
        {
            Reintentar();
        }

        private void txtClave_PasswordChanged(object sender, RoutedEventArgs e)
        {
            Reintentar();
        }

        private void Reintentar()
        {
            if (errorSesion)
            {
                RoutedEventArgs evento = new RoutedEventArgs(UsuarioClave.IniciarAutenticacionEvent);
                RaiseEvent(evento);
            }

            errorSesion = false;
        }
    }
}
